package com.paullorenc.rose.desktop.interfaces

import com.fazecast.jSerialComm.SerialPort
import com.fazecast.jSerialComm.SerialPortEvent
import com.fazecast.jSerialComm.SerialPortMessageListener
import com.paullorenc.rose.desktop.IncomingMessageBus
import kotlinx.coroutines.*

object SerialListener: SerialPortMessageListener {
    override fun getListeningEvents(): Int {
        return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
    }

    override fun getMessageDelimiter(): ByteArray {
        return byteArrayOf(0x0A.toByte())
    }

    override fun delimiterIndicatesEndOfMessage(): Boolean {
       return true
    }

    override fun serialEvent(event: SerialPortEvent?) {
        val delimitedMessage = event!!.receivedData
        var strDelim = String(delimitedMessage).replace("\n", "")
        strDelim = strDelim.replace("\r", "")
        GlobalScope.launch(Dispatchers.IO) {
            launch {
                IncomingMessageBus.postMessage(strDelim)
            }
        }
    }

}
object SerialInterface {
    private val comPort: SerialPort = SerialPort.getCommPort("/dev/ttyUSB0");
    init {
        comPort.openPort()
        comPort.setComPortTimeouts(SerialPort.TIMEOUT_WRITE_BLOCKING, 0, 0)
        comPort.baudRate = 115200
        comPort.addDataListener(SerialListener)
    }
    fun write(str: String) {
        val str = str + '\n'
        val bstr = str.toByteArray()
        comPort.writeBytes(bstr, bstr.size.toLong())
    }
    fun close() {
        if(comPort.isOpen) {
            comPort.closePort()
        }
    }
}


